<template>
    <div>
         <!-- 面包屑导航 -->
        <el-breadcrumb separator="/">
        <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item>角色管理</el-breadcrumb-item>
        <el-breadcrumb-item>角色列表</el-breadcrumb-item>
        </el-breadcrumb>
        <!-- 卡片视图 -->
       <el-card class="box-card">
           <!-- 添加角色按钮区域 -->
           <el-row>
               <el-button type="primary">添加角色</el-button>
           </el-row>
           <!-- 角色列表区域 -->
           <!-- 卡片视图 -->

           <el-table :data="rolesList" border stripe>
               <!-- 展开列 -->
               <el-table-column type="expand">
                 <template slot-scope="scope">
                     <!-- 栅格系统 -->
                     <el-row :class="['bdbottom',i1===0?'bdtop':'','vscenter']" v-for="(item1,i1) in scope.row.children" :key="i1">
                          <!-- 渲染一级权限 -->
                          <el-col :span="5">
                               <el-tag closable @close="removeRightById(scope.row,item1.id)"> {{item1.authName}}</el-tag>
                               <i class="el-icon-right"></i>
                          </el-col>
                          <!-- 渲染二级权限 -->
                          <el-col :span="19">
                              <!-- 通过for循环嵌套渲染二级 -->
                               <el-row :class="[i2===0?'':'bdtop','vscenter']" v-for="(item2,i2) in item1.children" :key="i2">
                                    <el-col :span="6">
                                        <el-tag type="success" closable @close="removeRightById(scope.row,item2.id)"> {{item2.authName}}</el-tag>
                                        <i class="el-icon-right"></i>
                                    </el-col>
                                    <el-row :span="18">
                                         <!-- 渲染三级权限 -->
                                         <el-tag closable @close="removeRightById(scope.row,item3.id)" type="warning" v-for="(item3,i3) in item2.children" :key="i3">{{item3.authName}}</el-tag>
                                    </el-row>
                               </el-row>
                          </el-col>
                     </el-row>
                     <pre>{{scope.row}}</pre>
                       
                  </template>
              </el-table-column>
               <!-- 索引 -->
             <el-table-column type="index"> </el-table-column>
             <el-table-column label="角色名称" prop="roleName">
             </el-table-column>
             <el-table-column label="角色描述" prop="roleDesc">
             </el-table-column>
             <el-table-column label="操作" width="300">
                <template slot-scope="scope">
                  <el-button size="mini" type="primary" icon="el-icon-edit">编辑</el-button>
                  <el-button size="mini" type="danger" icon="el-icon-delete">删除</el-button>
                  <el-button size="mini" type="warning" icon="el-icon-setting" @click="showSetRightDialog(scope.row)">分配权限</el-button>
               </template>
                <!-- <el-button size="mini" type="primary" icon="el-icon-edit">编辑</el-button>
                  <el-button size="mini" type="danger" icon="el-icon-delete">删除</el-button>
                  <el-button size="mini" type="warning" icon="el-icon-setting">分配</el-button>
                -->
             </el-table-column>
           </el-table>

       </el-card>

       <!-- 分配权限对话框 -->
       
            <el-dialog
            @close="setRightsDialogClosed"
            title="提示"
            :visible.sync="setRightDialogVisible"
            width="50%">
            <!-- 树形控件 -->
            <el-tree :data="rightsList" :props="treeProps" ref="treeRef" show-checkbox node-key="id" default-expand-all :default-checked-keys="defKeys"></el-tree>
            <span slot="footer" class="dialog-footer">
                <el-button @click="setRightDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="allotRights">确 定</el-button>
            </span>
            </el-dialog>
    </div>
</template>

<script>
import axios from 'axios'
export default {
    data(){
        return{
            // 所有角色列表
            rolesList:[],
            roleId:'',
            rightsId:'',
            roleChildren:[],
            setRightDialogVisible:false,
            rightsList:[],
            treeProps:{ //树形控件的绑定
              label:'authName',
              children:'children'
            },
            defKeys:[105,116] 
        }
    },
    created(){
        // 获取所有的权限
        this.getRightsList();
    },
    methods:{
        // 获取权限列表
      async getRightsList(){
         const res=  await axios.get('roles')
         console.log(res,"角色列表");
          if (res.data.meta.status !== 200) {
                this.$notify.error({
                title: '提示',
                message: '获取角色信息失败'
                });
            } else {
                this.rolesList = res.data.data
                console.log("角色数据",this.rolesList);
            }
        },
       async removeRight(){
             const res=  await axios.delete(`roles/${this.roleId}/rights/${this.rightsId}`)
              if (res.data.meta.status !== 200) {
                this.$notify.error({
                title: '提示',
                message: '删除权限失败'
                });
            } else {
               this.getRightsList();
            // 
            //   this.roleChildren=res.data
            }
        },
        removeRightById(role,rightsId){ //根据ID删除对应的权限
        this.roleChildren=role.children;
        this.roleId=role.id;
        this.rightsId=rightsId;
        console.log(this.roleId,"this.roleId****",this.rightsId,"this.rightsId");
        console.log(this.roleChildren," this.roleChildren");
        
        //  弹窗提示是否删除
         this.$confirm('此操作将永久删除该权限, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
            this.removeRight();
         role.children=this.roleChildren;
          this.$message({
            type: 'success',
            message: '删除成功!'
          });
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });          
        });

        },
      async showSetRightDialog(role){ //展示分配权限的对话框
        this.roleId=role.id
        // 获取所有权限的接口
         const res=  await axios.get('rights/tree')
         console.log(res);
           if (res.data.meta.status !== 200) {
                this.$notify.error({
                title: '提示',
                message: '获取权限失败'
                });
            } else {
             
             this.rightsList=res.data.data;
             console.log("获取权限列表成功",this.rightsList);
             //  递归获取三级节点的id
             this.getLeafKeys(role,this.defKeys);
            }
        
         this.setRightDialogVisible=!this.setRightDialogVisible;
        },
        getLeafKeys(node,arr){ //通过递归的形式，获取角色下所有三级权限的ID，并存到defKeys数组中
        //    如果当前node节点不包括children属性，则是三级节点
           if (!node.children) {
               return arr.push(node.id);
           }

           node.children.forEach(item => {
                this.getLeafKeys(item,arr)
           });
        },
        setRightsDialogClosed(){ //监听权限对话框关闭事件
           this.defKeys=[]
        },
       async allotRights(){ //点击为角色分配权限
           const keys=[
               ...this.$refs.treeRef.getCheckedKeys(), ...this.$refs.treeRef.getHalfCheckedKeys()
           ]

           console.log(keys);
           const idStr=keys.join(',')
           console.log(idStr,"idStr");
            // 获取付给权限的接口
         const res=  await axios.post(`roles/${this.roleId}/rights`, { rids:idStr })
         console.log(res,"res");
         
            if (res.data.meta.status !== 200) {
                    this.$notify.error({
                    title: '提示',
                    message: '分配权限失败'
                    });
                } 
                this.$message({
                    type: 'success',
                    message: '分配权限成功!'
                });
                this.getRightsList();
                this.setRightDialogVisible=false;
            
        }
    }
}
</script>

<style lang="less" scoped>
  .el-tag{
      margin: 7px;
  }
  .bdtop{
    border-top: 1px solid #eeeeee;
  }
  .bdbottom{
      border-bottom: 1px solid #eeeeee;
  }
  .vscenter{
     display: flex;
     align-items: center; 
  }
</style>

